package com.fan.gofast.compent;

import lombok.Data;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 多线程任务配置
 *
 */
@Data
@EnableAsync
@Configuration
public class CommonTaskExecutorConfig {

    private int coreSize = 8;

    private int maxSize = 16;

    private int queueCapacity = 200;

    private int keepAliveSeconds = 60;

    private String threadNamePrefix = "common-executor";

    private int awaitTerminationSeconds = 60;

    private boolean waitForTasksToCompleteOnShutdown = true;

    @Bean("commonTaskExecutor")
    public ThreadPoolTaskExecutor commonTaskExecutor() {
        ThreadPoolTaskExecutor poolTaskExecutor = new ThreadPoolTaskExecutor();
        poolTaskExecutor.setCorePoolSize(coreSize);
        poolTaskExecutor.setMaxPoolSize(maxSize);
        poolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        poolTaskExecutor.setQueueCapacity(queueCapacity);
        poolTaskExecutor.setThreadNamePrefix(threadNamePrefix);
        poolTaskExecutor.setAwaitTerminationSeconds(awaitTerminationSeconds);
        poolTaskExecutor.setWaitForTasksToCompleteOnShutdown(waitForTasksToCompleteOnShutdown);
        poolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        poolTaskExecutor.initialize();
        return poolTaskExecutor;
    }
}
